/*
Copyright (c) 2010 Andi Rustandi Djunaedi andird@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
package com.appspot.mobileirisnextbus.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.appspot.mobileirisnextbus.client.BusService;
import com.appspot.mobileirisnextbus.shared.Constants;
import com.appspot.mobileirisnextbus.shared.MobileIrisNextBusException;
import com.appspot.mobileirisnextbus.shared.Util;
import com.appspot.mobileirisnextbus.shared.data.Bus;
import com.appspot.mobileirisnextbus.shared.data.BusStop;
import com.google.common.base.Charsets;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class BusServiceImpl extends RemoteServiceServlet implements BusService {

    @Override
    public BusStop getBusAndTime(String busStopNum) throws MobileIrisNextBusException {
        // Escape data from the client to avoid cross-site script
        // vulnerabilities.
        busStopNum = Util.escapeHtml(busStopNum);
        final List<Bus> listOfBus = new ArrayList<Bus>();
        // get result from mobileiris website
        try {
            // get home page
            URL url = new URL(Constants.sbsMobileiris);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);

            if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
                // home page redirect result, don't follow it,
                // go retrieve list of services
                final String redirectResult = conn.getHeaderField(Constants.headerLocation);
                final String nextBusSelectionPage = redirectResult.replace(Constants.indexAspx,
                        Constants.svcList + busStopNum);
                url = new URL(nextBusSelectionPage);
                conn = (HttpURLConnection) url.openConnection();
                conn.setInstanceFollowRedirects(false);

                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    // get list of buses
                    final BufferedReader br = new BufferedReader(new InputStreamReader(
                            conn.getInputStream(), Charsets.UTF_8), Constants.bufferDefaultSize);
                    String line = br.readLine();
                    while (line != null) {
                        if (line.startsWith(Constants.svcLineStart)) {
                            final String busNum = this.getBusNum(line).trim();
                            final List<String> listOfTimes = this.getBusTime(busStopNum, busNum);
                            final Bus b = new Bus();
                            b.setBusNum(busNum);
                            b.setTimes(listOfTimes);
                            listOfBus.add(b);
                        }
                        line = br.readLine();
                    }
                } else {
                    // Server returned unexpected HTTP code.
                    throw new MobileIrisNextBusException(Constants.msgNotExpected
                            + conn.getResponseCode());
                }
            } else {
                // Server returned unexpected HTTP code.
                throw new MobileIrisNextBusException(Constants.msgNotExpected
                        + conn.getResponseCode());
            }
        } catch (final MalformedURLException e) {
            e.printStackTrace();
            throw new MobileIrisNextBusException(e);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new MobileIrisNextBusException(e);
        } catch (final Exception e) {
            e.printStackTrace();
            throw new MobileIrisNextBusException(e);
        }
        final BusStop bs = new BusStop();
        bs.setBuses(listOfBus);
        bs.setBusStopNum(busStopNum);
        return bs;
    }

    @Override
    public List<Bus> getBuses(String busStopNum) throws MobileIrisNextBusException {
        // Escape data from the client to avoid cross-site script
        // vulnerabilities.
        busStopNum = Util.escapeHtml(busStopNum);
        final List<Bus> listOfBus = new ArrayList<Bus>();
        // get result from mobileiris website
        try {
            // get home page
            URL url = new URL(Constants.sbsMobileiris);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);

            if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
                // home page redirect result, don't follow it,
                // go retrieve list of services
                final String redirectResult = conn.getHeaderField(Constants.headerLocation);
                final String goToInputPage = redirectResult.replace(Constants.indexAspx,
                        Constants.nextBus);
                url = new URL(goToInputPage);
                conn = (HttpURLConnection) url.openConnection();
                conn.setInstanceFollowRedirects(false);

                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    String cookie = conn.getHeaderField(Constants.setCookie);
                    cookie = cookie.substring(0, 22);

                    // get resp body
                    BufferedReader br = new BufferedReader(new InputStreamReader(
                            conn.getInputStream(), Charsets.UTF_8), Constants.bufferDefaultSize);
                    String line = br.readLine();
                    String resp = Constants.blank;
                    while (line != null) {
                        if (line.startsWith(Constants.formLineStart)) {
                            resp = line;
                        }
                        line = br.readLine();
                    }

                    // input busstop and svc no, using POST
                    final String postAction = this.getPostAction(resp);
                    final String postUrl = goToInputPage.replace(Constants.nextBus, postAction);
                    url = new URL(postUrl);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty(Constants.cookie, cookie);
                    conn.setDoOutput(true);
                    conn.setRequestMethod(Constants.httpPost);
                    conn.setInstanceFollowRedirects(true);

                    String out = Constants.blank;
                    out += Constants.hiddenEt + Constants.eq + Constants.amp;
                    out += Constants.busStopPostParam + Constants.eq + busStopNum + Constants.amp;
                    out += Constants.btnGoParam + Constants.eq + Constants.btnGoVal + Constants.amp;
                    final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                            conn.getOutputStream(), Charsets.UTF_8));
                    bw.write(out);
                    bw.close();

                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        // get list of buses
                        br = new BufferedReader(new InputStreamReader(conn.getInputStream(),
                                Charsets.UTF_8), Constants.bufferDefaultSize);
                        line = br.readLine();
                        while (line != null) {
                            if (line.startsWith(Constants.svcLineStart)) {
                                final String busNum = this.getBusNum(line).trim();
                                final Bus b = new Bus();
                                b.setBusNum(busNum);
                                listOfBus.add(b);
                            }
                            line = br.readLine();
                        }
                    } else {
                        // Server returned unexpected HTTP code.
                        throw new MobileIrisNextBusException(Constants.msgNotExpected
                                + conn.getResponseCode());
                    }
                } else {
                    // Server returned unexpected HTTP code.
                    throw new MobileIrisNextBusException(Constants.msgNotExpected
                            + conn.getResponseCode());
                }
            } else {
                // Server returned unexpected HTTP code.
                throw new MobileIrisNextBusException(Constants.msgNotExpected
                        + conn.getResponseCode());
            }
        } catch (final MalformedURLException e) {
            e.printStackTrace();
            throw new MobileIrisNextBusException(e);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new MobileIrisNextBusException(e);
        } catch (final Exception e) {
            e.printStackTrace();
            throw new MobileIrisNextBusException(e);
        }
        return listOfBus;
    }

    private String getBusNum(final String line) {
        final int idxEnd = line.indexOf(Constants.svcLineIdxEnd);
        final int idxStart = line.lastIndexOf(Constants.svcLineIdxStart, idxEnd) + 2;
        return line.substring(idxStart, idxEnd);
    }

    @Override
    public List<String> getBusTime(final String busStop, final String svc)
            throws MobileIrisNextBusException {
        final List<String> listOfTimes = new ArrayList<String>();

        // Escape data from the client to avoid cross-site script
        // vulnerabilities.
        final String inputBusStop = Util.escapeHtml(busStop);
        final String inputSvc = Util.escapeHtml(svc);

        // get result from mobileiris website
        try {
            // get home page
            URL url = new URL(Constants.sbsMobileiris);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);

            if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
                // home page redirect result, don't follow it,
                // go retrieve list of services
                final String redirectResult = conn.getHeaderField(Constants.headerLocation);
                final String goToInputPage = redirectResult.replace(Constants.indexAspx,
                        Constants.nextBus);
                url = new URL(goToInputPage);
                conn = (HttpURLConnection) url.openConnection();
                conn.setInstanceFollowRedirects(false);

                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    String cookie = conn.getHeaderField(Constants.setCookie);
                    cookie = cookie.substring(0, 22);

                    // get resp body
                    final BufferedReader br = new BufferedReader(new InputStreamReader(
                            conn.getInputStream(), Charsets.UTF_8), Constants.bufferDefaultSize);
                    String line = br.readLine();
                    String resp = Constants.blank;
                    while (line != null) {
                        if (line.startsWith(Constants.formLineStart)) {
                            resp = line;
                        }
                        line = br.readLine();
                    }

                    // input busstop and svc no, using POST
                    final String postAction = this.getPostAction(resp);
                    final String postUrl = goToInputPage.replace(Constants.nextBus, postAction);
                    url = new URL(postUrl);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty(Constants.cookie, cookie);
                    conn.setDoOutput(true);
                    conn.setRequestMethod(Constants.httpPost);
                    conn.setInstanceFollowRedirects(true);

                    String out = Constants.blank;
                    out += Constants.hiddenEt + Constants.eq + Constants.amp;
                    out += Constants.busStopPostParam + Constants.eq + inputBusStop + Constants.amp;
                    out += Constants.busSvcParam + Constants.eq + inputSvc + Constants.amp;
                    out += Constants.btnGoParam + Constants.eq + Constants.btnGoVal + Constants.amp;
                    final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                            conn.getOutputStream(), Charsets.UTF_8));
                    bw.write(out);
                    bw.close();

                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        // get resp body
                        final BufferedReader resultBr = new BufferedReader(new InputStreamReader(
                                conn.getInputStream(), Charsets.UTF_8), Constants.bufferDefaultSize);
                        String resultLine = resultBr.readLine();
                        boolean nextFound = false;
                        boolean subsequentFound = false;
                        boolean busNumFound = false;
                        while ((resultLine != null) && (!nextFound || !subsequentFound)) {
                            if (!busNumFound) {
                                if (resultLine.startsWith(Constants.serviceNumLineStart)) {
                                    if (this.isCorrectBusNum(inputSvc, resultLine)) {
                                        busNumFound = true;
                                    }
                                }
                            } else {
                                if (resultLine.startsWith(Constants.nextBusValStart)) {
                                    listOfTimes.add(this.getNextBusTime(resultLine));
                                    nextFound = true;
                                } else if (resultLine.startsWith(Constants.subsequentBusValStart)) {
                                    listOfTimes.add(this.getSubsequentBusTime(resultLine));
                                    subsequentFound = true;
                                }
                            }
                            resultLine = resultBr.readLine();
                        }
                    } else {
                        // Server returned unexpected HTTP code.
                        throw new MobileIrisNextBusException(Constants.msgNotExpected
                                + conn.getResponseCode());
                    }
                } else {
                    // Server returned unexpected HTTP code.
                    throw new MobileIrisNextBusException(Constants.msgNotExpected
                            + conn.getResponseCode());
                }
            } else {
                // Server returned unexpected HTTP code.
                throw new MobileIrisNextBusException(Constants.msgNotExpected
                        + conn.getResponseCode());
            }
        } catch (final MalformedURLException e) {
            e.printStackTrace();
            throw new MobileIrisNextBusException(e);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new MobileIrisNextBusException(e);
        } catch (final Exception e) {
            e.printStackTrace();
            throw new MobileIrisNextBusException(e);
        }
        return listOfTimes;
    }

    /**
     * @param input
     * @return
     */
    private String getNextBusTime(final String input) {
        final int idxStart = input.indexOf(Constants.nextBusValStart)
                + Constants.nextBusValStart.length();
        final int idxEnd = input.indexOf(Constants.busValBr);
        final String result = input.substring(idxStart, idxEnd).trim();
        return result;
    }

    /**
     * @param input
     * @return
     */
    private String getPostAction(final String input) {
        final int idxStart = input.indexOf(Constants.actionIdxStart);
        final int idxEnd = input.indexOf(Constants.actionIdxEnd);
        final String result = input.substring(idxStart, idxEnd);
        return result;
    }

    /**
     * @param input
     * @return
     */
    private String getSubsequentBusTime(final String input) {
        final int idxStart = input.indexOf(Constants.subsequentBusValStart)
                + Constants.subsequentBusValStart.length();
        final int idxEnd = input.indexOf(Constants.busValBr);
        final String result = input.substring(idxStart, idxEnd).trim();
        return result;
    }

    private boolean isCorrectBusNum(String busNum, String line) {
        final int idxStart = line.indexOf(Constants.serviceNumLineStart)
                + Constants.serviceNumLineStart.length();
        final int idxEnd = line.indexOf(Constants.serviceNumLineEnd);
        line = line.substring(idxStart, idxEnd);

        // trim leading zeros
        while (busNum.startsWith(Constants.zero)) {
            busNum = busNum.substring(1);
        }

        final boolean result = busNum.equals(line);
        return result;
    }

}
